//
// Created by Administrator on 2021/5/28.
//

//给定一个二叉搜索树的根节点 root ，和一个整数 k ，请你设计一个算法查找其中第 k 个最小元素（从 1 开始计数）。


#include <vector>
#include <iostream>
#include <stack>

using namespace std;

// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int kthSmallest(TreeNode *root, int k) {
        // 递归 需要遍历整棵树
        vector<int> v;
        dfs(v, root);
        return v[k - 1];
    }

    void dfs(vector<int> &v, TreeNode *root) {
        if (root == nullptr) return;
        dfs(v, root->left);
        v.push_back(root->val);
        dfs(v, root->right);
    }

    int kthSmallest2(TreeNode *root, int k) {
        // 借助栈实现 迭代 不需要全部遍历
        stack<TreeNode *> st;
        int cnt = 1;
        while (root != nullptr || !st.empty()) {
            if (root != nullptr) {
                st.push(root);
                root = root->left;
            } else {
                TreeNode *t = st.top();
                st.pop();
                if (cnt++ == k)
                    return t->val;
                root = t->right;
            }
        }
        return -1;
    }

};

int main() {
    auto n1 = TreeNode(3), n2 = TreeNode(1), n3 = TreeNode(4), n4 = TreeNode(2);
    n1.left = &n2;
    n1.right = &n3;
    n2.right = &n4;
    Solution sol;
    cout << sol.kthSmallest2(&n1, 4) << endl;
}